package com.jk.wh.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.jk.OrderBean;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("pay")
public class PayController {

    private final String APP_ID = "2021000117645238";
    private final String APP_PRIVATE_KEY = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDNczwRL1BwGckLu/1YgEOkSWucU+mAoNff5/c/HgzwGgToJzEUS5l6sEy9Rx1kWAF4ja3LkO3vUxdtQW6XpkDi9v9SdNlhJlVYXv2K2R0wgC8sRobPDWv/a+LxAnyMVQPs3HNFUDjK/QVmQ1UEdHMGZuyDReIZE5fKlhYoQ/+Iuz0+nx0/Qk9OQ4ZIvlTa/DYo8Z0mbjbVit1m1FXyWaPYfak9Ojn0XhEgEfNnql310kkjOczXDL3q3njNYOavL0GxUHKgoHmQp9NRl1mX3jHKdrXvFzmcvn2NqapA49lnWBenElO0OFHogUAsxeUrIbnSwSMgSvSVZEJNeHCuJDCpAgMBAAECggEAEYoj96eda2SYKFtNPq/8llr6R+dWCPgyVdg84HOVUS43ewZVh1EI8lN4ybP3i2iD/6HA05804PisCFTMtz+nTHkfxQ9au5OFN70sUh1FA6392P7QZX7U2IKCZmb68RQU+LS9Vo6JurKtMlTPPkkexM4mpPJjYhatH8t+asObXjXO1NTG7MZigiAdpuS/NLBkj2r4OvjJ9IDOyguaZ9So45Hg3W1zpqVqWYLuFIN4VMNpB82L9gDFCJGCT2MUo6ZHZCQ8qafCX6O1QIpgXaD/o4IjVJesdwrAnX/55csbyJvE7Yaq6Q2JzNFYs1qSKM6Sm9CmZPDkurVHDiV5XIVpAQKBgQDnVW2ww+VeG9DE4BXG+LTOpjSCKfZDjoJf1dnqg7SJ02mXMltD1tPp9QrHIHnaohLioyWjbAx/e1j3hBGDhPAIMdW/Vh+tfBCvFYWLXr59jqnCY03I0NqWOm6eoyLCyU+36f+2FBn9rZWvtc4UeoN6x2NREYNohVdmoql3lZu7SQKBgQDjW0dOTdKQ0Dqrfd7cbO9zmUWQNqsP6CXaFwXWerim47ATWvlEWimEsebAUkhnf1GBiCaoXQMf8n5fbqyW4XRMd5SnCJiuF7Kw65pvR+6M/40hW/j6QgUjNQFUeA0+h1vOi0ONwt8xk8UbNUBQSKEEsFkBtSHKlRsZR627R+ZqYQKBgQCzYqeAnyfJ5j/pquq4NDvg0zl8hhWVJXkr36TwGdlx1yLWQBJNdNU3YvFMoH5db7i9Tk3tf+fhI0FGDn+WQQvxDtP1X0+JM9+sJUA9ZubIbkxtlJvI0UvvmrgVA+P8sCbFMws7ojLVaDne21hGwQobt2nof3ArKNsxl4laVgVBIQKBgFWxy/ipwJowwkxtTxkKPl72AJBQ6r0+JTZEw0CKVRsiavWArr+itE99tpn66auJA7GtHdUL6eeawSM7VfYw2GMSF4e158aGzCV/SGB1Xmbq08klH31EcSdKDUxHS8arwmDhgP7n2rSXHA4bTjh0h6x6w7GvEiOHfAVVTRhwC1tBAoGBAK3qyAVxVPtZi1iH0kHibfRmaPo351wlvhSR/DUz6OMngr7BDI05tXX2wJswon6xo3aDNiqdisbiCG27xfk5GFvR6pyu27vBNofiqblij84kipZXQESdc+1II+22abtYZ4UMFg1sZ0M4IIizvcoJMYQUuJXN1B/js0EkfcPMMEdk";
    private final String CHARSET = "UTF-8";
    private final String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuKYnAsw5B2pkb3ShmGFJOGDBggUHlFQCYYGq1tfDl4kCzoxy0fX2T3rLA7FpUU9K++kNgh0zpHVB7Yy6li/Wvj0pDHbUenRVlDvs9pglvLEDQvYEXJRrJI/kYdOFVcxuMcizQZwly/z8A7pixY4GmhKhBDkVjaA0jP1wN6cLt8URu2se5fdN3vrmkh2lgtceYU8u8qRAkC0VmRvtQLUDneSTYELmAwjfL+hjkQh8RS3uHIKqJWUs8OjDZZWIXkwD9PKvHgNU5hSkEf/ZAxzzlyuIpUMlMsQ+3fIxuqE3D7WrITRKyhyER1bRFoc7lNL3Ku+eLE62prgHa6gN7pgkiQIDAQAB";
    //这是沙箱接口路径,正式路径为https://openapi.alipay.com/gateway.do
    private final String GATEWAY_URL ="https://openapi.alipaydev.com/gateway.do";
    private final String FORMAT = "JSON";
    //签名方式
    private final String SIGN_TYPE = "RSA2";
    //支付宝异步通知路径,付款完毕后会异步调用本项目的方法,必须为公网地址
    private final String NOTIFY_URL = "http://127.0.0.1:8084/movie/saveOrder";
    //支付宝同步通知路径,也就是当付款完毕后跳转本项目的页面,可以不是公网地址
    private final String RETURN_URL = "http://127.0.0.1:8084/movie/saveOrder";



    @RequestMapping("aliapy")
    public void alipay(OrderBean order, HttpServletResponse httpResponse) throws IOException {

        String returnurl = "http://127.0.0.1:8084/movie/saveOrder?orderId="+order.getOrderId()+"&orderPrice="+order.getOrderPrice()+"&phone="+order.getPhone();
        SecureRandom r= new SecureRandom();
        //实例化客户端,填入所需参数
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //在公共参数中设置回跳和通知地址
        request.setReturnUrl(NOTIFY_URL+"?orderId="+order.getOrderId()+"&orderPrice="+order.getOrderPrice()+"&phone="+order.getPhone());
        request.setNotifyUrl(RETURN_URL+"?orderId="+order.getOrderId()+"&orderPrice="+order.getOrderPrice()+"&phone="+order.getPhone());

        //商户订单号，商户网站订单系统中唯一订单号，必填
        //生成随机Id
        String out_trade_no = order.getOrderId();
        //付款金额，必填
        String total_amount =Double.toString(order.getOrderPrice());
        //订单名称，必填
        String subject ="影片订单";
        //商品描述，可空
        String body = "";
        request.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"orderId\":\""+ order.getOrderId() +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }



    @RequestMapping(value = "/returnUrl", method = RequestMethod.GET)
    public String returnUrl(HttpServletRequest request, HttpServletResponse response)
            throws IOException, AlipayApiException {
        System.out.println("=================================同步回调=====================================");

        // 获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("utf-8"), "utf-8");
            params.put(name, valueStr);
        }

        System.out.println(params);//查看参数都有哪些
        boolean signVerified = AlipaySignature.rsaCheckV1(params, ALIPAY_PUBLIC_KEY, CHARSET, SIGN_TYPE); // 调用SDK验证签名
        //验证签名通过
        if(signVerified){
            // 商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

            // 支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");

            // 付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");

            System.out.println("商户订单号="+out_trade_no);
            System.out.println("支付宝交易号="+trade_no);
            System.out.println("付款金额="+total_amount);

            //支付成功，修复支付状态
            //payService.updateById(Integer.valueOf(out_trade_no));

            return "ok";//跳转付款成功页面
        }else{
            return "no";//跳转付款失败页面
        }

    }

}
